import React, { useState, useEffect, useRef } from 'react'
import PageHeader from '../components/PageHeader'
import { wapper } from '../utils/hoc'
import { useRouterHook } from '../utils/hooks'
import { getDoctorDetail, appointmentAdd } from '../utils/api'
import { Form, Button, Input, DatePicker, Toast, Avatar, Dialog } from 'antd-mobile'
import { FormInstance } from 'antd-mobile/es/components/form'
const baseUrl = import.meta.env.VITE_API_BASE_URL
const AppointAdd: React.FC = () => {
  const { navigate } = useRouterHook()
  const { id: patientid, role_id } = JSON.parse(localStorage.getItem('userLoginInfo') || '{}')
  const formRef = useRef<FormInstance>(null)
  const [visible, setVisible] = useState(false)
  const { location: { state } } = useRouterHook()
  const { doctorid } = state
  const [doctor, setDoctor] = useState<Partial<DoctorRowType>>({})
  useEffect(() => {
    if (role_id !== 2) {
      Dialog.alert({ content: '只有患者账号可以使用预约功能!' }).then(() => { })
      return navigate('/')
    }
    // 查询医生信息
    (async () => {
      const { data } = await getDoctorDetail(doctorid)
      if (data.code === 200) {
        setDoctor(data.data)
      }
    })()
  }, [])
  const submit = async (values: AppointRowType) => {
    console.log(values, 'values');
    const { name, phone } = values
    // 获取时间戳
    const appoint_time = new Date(values.appoint_time).getTime()
    const payload = { appoint_time, name, phone, doctorid, patientid }
    const { data } = await appointmentAdd(payload)
    if (data.code === 200) {
      Toast.show({ icon: "success", content: data.msg })
      // 自动跳转到预约列表页面
      navigate('/appoint')
      return
    }
    Toast.show({ icon: "fail", content: data.msg })
  }
  return (
    <div>
      <PageHeader>
        <h4>立即预约</h4>
      </PageHeader>
      {/* 时间选择器 */}
      <DatePicker
        visible={visible}
        onClose={() => {
          setVisible(false)
        }}
        precision='minute'
        onConfirm={(val: Date) => {
          // Toast.show(val.toString())
          formRef.current?.setFieldValue('appoint_time', val.toLocaleString())
        }}
      />
      <Form onFinish={submit} mode="card" layout="vertical" ref={formRef}
        footer={<Button shape="rounded" type="submit" block color="primary">立即预约</Button>}>
        <Form.Item label="医生头像">
          <Avatar src={`${baseUrl + doctor.avatar}`}></Avatar>
        </Form.Item>
        <Form.Item label="医生姓名">
          {doctor.name}
        </Form.Item>
        <Form.Item label="医生电话">
          {doctor.phone}
        </Form.Item>
        <Form.Item name="appoint_time" label="就诊时间"
          rules={[{ required: true, message: '请选择就诊时间' }]}>
          <Input onClick={() => setVisible(true)} placeholder="请选择就诊时间"></Input>
        </Form.Item>
        <Form.Item name="name" label="患者姓名"
          rules={[{ required: true, message: '请输入患者姓名' }]}>
          <Input placeholder="请输入患者姓名"></Input>
        </Form.Item>
        <Form.Item name="phone" label="患者电话"
          rules={[{ required: true, message: '请输入患者联系电话', min: 11, max: 11 }]}>
          <Input placeholder="请输入患者电话" maxLength={11}></Input>
        </Form.Item>
      </Form>
    </div>
  )
}

export default wapper(AppointAdd, { title: '立即预约', requireLogin: true })